package algorithm.acwing.t852;

import java.io.*;
import java.util.*;

public class Main {
    static class io {
        // 读
        static InputStreamReader ins = new InputStreamReader(System.in);
        static StreamTokenizer in = new StreamTokenizer(ins);
        static BufferedReader br = new BufferedReader(ins);

        // 写
        public static PrintWriter out = new PrintWriter(System.out);


        public static int readInt() {
            try {
                in.nextToken();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return (int) in.nval;
        }

        public static String readLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        public static double readDouble() {
            try {
                in.nextToken();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return in.nval;
        }
    }
    static class Edge {
        int v;
        int p;
        public Edge(int v, int p) {
            this.p = p;
            this.v = v;
        }
        public int getV() {
            return v;
        }
    }
    static int N = 200010;
    static ArrayList<Edge>[] edges = new ArrayList[N];
    static int[] dist = new int[N], st = new int[N];
    public static void main(String[] args) {
        Arrays.setAll(edges, i -> new ArrayList<Edge>());
        Arrays.fill(dist, Integer.MAX_VALUE/2);
        dist[1] = 0;
        int n = io.readInt(), m = io.readInt();
        for(int i = 1; i <= m; i ++) {
            int a = io.readInt(), b = io.readInt(), c = io.readInt();
            edges[a].add(new Edge(c,b));
        }
        PriorityQueue<Edge> q = new PriorityQueue<>(Comparator.comparingInt(Edge::getV));
        q.add(new Edge(0,1));

        while(!q.isEmpty()) {
            Edge e = q.poll();
            if(dist[e.p] == e.v) {
                for(Edge edge : edges[e.p]) {
                   int p = edge.p;
                   if(dist[p] > dist[e.p] + edge.v) {
                       dist[p] = dist[e.p] + edge.v;
                       q.add(new Edge(dist[p],edge.p));
                   }
                }
            }
        }
        if(dist[n] >= Integer.MAX_VALUE/2) {
            io.out.println(-1);
        }else {
            io.out.println(dist[n]);
        }
        io.out.flush();

    }
}
